package com.chinawlx.wlxteacher.ui.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chinawlx.wlxteacher.R;
import com.chinawlx.wlxteacher.network.WLXHttpRxHelper;
import com.chinawlx.wlxteacher.network.bean.WLXClazzHomeWorkBean;
import com.chinawlx.wlxteacher.ui.activity.WLXCommentListActivity;
import com.chinawlx.wlxteacher.ui.adapter.WLXHomeworkCommentAdapter;
import com.chinawlx.wlxteacher.utils.WLXConstant;
import com.chinawlx.wlxteacher.utils.WLXDateUtil;
import com.chinawlx.wlxteacher.utils.WLXGreenDaoUtil;
import com.chinawlx.wlxteacher.utils.WLXLogUtil;
import com.chinawlx.wlxteacher.utils.WLXNetUtil;
import com.chinawlx.wlxteacher.widget.WLXCustomToast;
import com.chinawlx.wlxteacher.wlx_homework;
import com.chinawlx.wlxteacher.wlx_homeworkDao;
import com.google.gson.Gson;

import java.util.List;

import cn.bingoogolapple.refreshlayout.BGAMeiTuanRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;
import rx.Subscriber;

/**
 * 作者:黄帅
 * 时间:16/9/24
 * 描述:作业点评界面
 * 思路:
 * 1. 拉取第一页数据-->返回所有未点评和部分历史数据
 * 2. 根据状态判断,正常的存入数据库,被删除的,查询数据库有没有,有就删除掉
 * 3. 显示数据,拉取数据库第index页的数据,index=1 拉取所有的的未点评和历史数据展示
 * 4. 下拉刷新,index=1,返回第一步
 * 5. 上拉加载,index++,只是刷新历史数据,返回1
 */
public class WLXHomeworkCommentFragment extends WLXBaseFragment implements BGARefreshLayout
        .BGARefreshLayoutDelegate {

    private ListView mListView;
    private TextView mNoCommentNum;//未点评数
    private TextView mReplyNum;//回复数
    private RelativeLayout mRlContainerEmpty;
    private TextView mTvMsg;

    private int paging_index = 1;//分页索引
    private int paging_size = 10;//每页大小
    private WLXHomeworkCommentAdapter mAdapter;
    private boolean mHasMoreData = true;
    private View mHeadView;
    private WLXLoadingFragment mLoadingFragment;

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle
            savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_job_comment, null);
        initView(view);
        return view;
    }

    private void initView(View view) {
        mRlContainerEmpty = (RelativeLayout) view.findViewById(R.id.rl_container_empty);
        mTvMsg = (TextView) view.findViewById(R.id.tv_msg);

        mRefreshLayout = (BGARefreshLayout) view.findViewById(R.id.rl_modulename_refresh);
        mListView = (ListView) view.findViewById(R.id.job_comment_listview);

        mHeadView = LayoutInflater.from(getContext()).inflate(R.layout.header_job_comment,
                null);
        mNoCommentNum = (TextView) mHeadView.findViewById(R.id.tv_no_comment_num);
        mReplyNum = (TextView) mHeadView.findViewById(R.id.tv_reply_num);
        mListView.addHeaderView(mHeadView);
        mHeadView.setVisibility(View.INVISIBLE);

        initAdapter();
        initRefreshLayout();
        mRefreshLayout.beginRefreshing();

        mReplyNum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(WLXCommentListActivity.class);
            }
        });
    }

    private void initAdapter() {
        mAdapter = new WLXHomeworkCommentAdapter(getActivity());
        mListView.setAdapter(mAdapter);
    }

    //--------刷新内容 start---------
    private BGARefreshLayout mRefreshLayout;

    private void initRefreshLayout() {
        mRefreshLayout.setDelegate(this);
        BGAMeiTuanRefreshViewHolder meiTuanRefreshViewHolder = new BGAMeiTuanRefreshViewHolder
                (this.getContext(), true);
        meiTuanRefreshViewHolder.setPullDownImageResource(R.drawable.yuanq);
        meiTuanRefreshViewHolder.setChangeToReleaseRefreshAnimResId(R.drawable
                .bga_refresh_mt_change_to_release_refresh);
        meiTuanRefreshViewHolder.setRefreshingAnimResId(R.drawable.bga_refresh_mt_refreshing);

        mRefreshLayout.setRefreshViewHolder(meiTuanRefreshViewHolder);
    }

    //开始刷新
    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        if (WLXNetUtil.CheckNetwork(getActivity())) {
            paging_index = 1;
            loadDataFromNet();
        } else {
//            WLXCustomToast.show("无网络!");
            mRefreshLayout.endRefreshing();
            initDataFromDataBase();
        }
    }


    //处理上拉加载,在这里上拉加载更多,
    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        if (WLXNetUtil.CheckNetwork(getActivity())) {
            if (mHasMoreData) {
                paging_index++;
                loadDataFromNet();
                return true;
            } else {
                WLXCustomToast.show("没有更多数据");
                return false;
            }
        } else {
//            WLXCustomToast.show("无网络!");
            initDataFromDataBase();
            return false;
        }
    }
    //-----------刷新 end------


    private void loadDataFromNet() {
        mLoadingFragment = WLXLoadingFragment.getInstance();
        mLoadingFragment.show(getActivity().getSupportFragmentManager(), "homework1");
        WLXHttpRxHelper.getInstance().getClassHomeWork(WLXConstant.GRADE_ID, paging_index + "",
                paging_size +
                        "", new Subscriber<WLXClazzHomeWorkBean>() {
                    @Override
                    public void onCompleted() {
                        // 展示 ，取数据
                        initDataFromDataBase();
                        mLoadingFragment.dismiss();
                    }

                    @Override
                    public void onError(Throwable e) {
                        // 网络异常 ，请求时间过长
                        onCompleted();
                    }

                    @Override
                    public void onNext(WLXClazzHomeWorkBean classHomeWorkBean) {
                        insert2Db(classHomeWorkBean);
                    }
                });
    }

    //向homework表中插入数据
    private void insert2Db(WLXClazzHomeWorkBean classHomeWorkBean) {
        //history_list
        List<WLXClazzHomeWorkBean.DataBean.HistoryListBean> history_list =
                classHomeWorkBean.getData().getHistory_list();
        WLXLogUtil.printE("history_list条数:" + history_list.size());

        //历史数据
        for (WLXClazzHomeWorkBean.DataBean.HistoryListBean historyList : history_list) {
            //status_code=deleted 删除数据 or duration!=urls.size放弃这条数据

            if (historyList.getExtend().getResource_url() != null) {
                int duration = historyList.getExtend().getDuration();
                int size = historyList.getExtend().getResource_url().size();
                if (duration < size) continue;
            }

            String homework_id = Integer.toString(historyList.getId());
            String status_code = historyList.getStatus().getKey();
            if ("deleted".endsWith(status_code)) {
                List<wlx_homework> wlx_homeworks = WLXGreenDaoUtil.getHomeWorkDao()
                        .queryBuilder().where(wlx_homeworkDao.Properties.Homework_id.eq
                                (homework_id)).list();
                if (wlx_homeworks.size() > 0) {
                    WLXGreenDaoUtil.getHomeWorkDao().delete(wlx_homeworks.get(0));
                }
                continue;
            }

            WLXConstant.HOMEWORK_ID = homework_id;
            int teacher_user_id = historyList.getTeacher_user_id();
            int family_user_id = historyList.getFamily_user_id();
            int student_id = historyList.getStudent_id();
            int grade_id = historyList.getGrade_id();
            int schedule_id = historyList.getSchedule_id();
            String content = historyList.getContent();
            String homework_content_code = historyList.getHomework_content().getKey();
            int is_teacher_comment = historyList.isIs_teacher_comment() ? 1 : 0;
            int is_family_reply = historyList.isIs_family_reply() ? 1 : 0;
            int is_replied = historyList.isIs_replied() ? 1 : 0;
            String extend_info = new Gson().toJson(historyList.getExtend());
            long last_modified_date = WLXDateUtil.getStringToDate(historyList
                    .getLast_modified_date());
            long creation_date = WLXDateUtil.getStringToDate(historyList.getCreation_date
                    ());
            //插入作业数据
            wlx_homework wlxHomeWork = new wlx_homework(homework_id, teacher_user_id,
                    family_user_id, student_id, grade_id, schedule_id, content,
                    homework_content_code, status_code, is_teacher_comment,
                    is_family_reply, is_replied, extend_info, last_modified_date,
                    creation_date);
            //1,查询homework_id这条记录,homework_id是唯一的
            List<wlx_homework> wlx_homeworks = WLXGreenDaoUtil.getHomeWorkDao()
                    .queryBuilder().where(wlx_homeworkDao.Properties.Homework_id.eq
                            (WLXConstant.HOMEWORK_ID)).list();
            if (wlx_homeworks.size() > 0) {
                WLXLogUtil.printE("homework_id查询到的指定id记录信息:" + historyList.toString());
                //2, 有这条记录, 就去对比last_modified_date, 如果服务器时间更新, 就update表数据
                if (last_modified_date > wlx_homeworks.get(0).getLast_modified_date()) {
                    WLXGreenDaoUtil.getHomeWorkDao().update(wlxHomeWork);
                }
            } else {
                //无数据,就直接插入数据
                WLXGreenDaoUtil.getHomeWorkDao().insert(wlxHomeWork);
            }
        }

        //home_work_list
        List<WLXClazzHomeWorkBean.DataBean.HomeworkListBean> homework_list =
                classHomeWorkBean.getData().getHomework_list();
        WLXLogUtil.printE("homework_list条数:" + homework_list.size());

        for (WLXClazzHomeWorkBean.DataBean.HomeworkListBean homeworkList : homework_list) {
            //status_code=deleted 删除数据 or duration!=urls.size放弃这条数据

            if (homeworkList.getExtend().getResource_url() != null) {
                int duration = homeworkList.getExtend().getDuration();
                int size = homeworkList.getExtend().getResource_url().size();
                if (duration < size) continue;
            }

            String homework_id = Integer.toString(homeworkList.getId());
            String status_code = homeworkList.getStatus().getKey();
            if ("deleted".endsWith(status_code)) {
                List<wlx_homework> wlx_homeworks = WLXGreenDaoUtil.getHomeWorkDao()
                        .queryBuilder().where(wlx_homeworkDao.Properties.Homework_id.eq
                                (homework_id)).list();
                if (wlx_homeworks.size() > 0) {
                    WLXGreenDaoUtil.getHomeWorkDao().delete(wlx_homeworks.get(0));
                }
                continue;
            }

            WLXConstant.HOMEWORK_ID = homework_id;
            int teacher_user_id = homeworkList.getTeacher_user_id();
            int family_user_id = homeworkList.getFamily_user_id();
            int student_id = homeworkList.getStudent_id();
            int grade_id = homeworkList.getGrade_id();
            int schedule_id = homeworkList.getSchedule_id();
            String content = homeworkList.getContent();
            String homework_content_code = homeworkList.getHomework_content().getKey();
            int is_teacher_comment = homeworkList.isIs_teacher_comment() ? 1 : 0;
            int is_family_reply = homeworkList.isIs_family_reply() ? 1 : 0;
            int is_replied = homeworkList.isIs_replied() ? 1 : 0;
            String extend_info = new Gson().toJson(homeworkList.getExtend());
            long last_modified_date = WLXDateUtil.getStringToDate(homeworkList
                    .getLast_modified_date());
            long creation_date = WLXDateUtil.getStringToDate(homeworkList
                    .getCreation_date());
            //插入作业数据
            wlx_homework wlxHomeWork = new wlx_homework(homework_id, teacher_user_id,
                    family_user_id, student_id, grade_id, schedule_id, content,
                    homework_content_code, status_code, is_teacher_comment,
                    is_family_reply, is_replied, extend_info, last_modified_date,
                    creation_date);
            //1,查询homework_id这条记录,homework_id是唯一的
            List<wlx_homework> wlx_homeworks = WLXGreenDaoUtil.getHomeWorkDao()
                    .queryBuilder().where(wlx_homeworkDao.Properties.Homework_id.eq
                            (WLXConstant.HOMEWORK_ID)).list();
            if (wlx_homeworks.size() > 0) {
                WLXLogUtil.printE("homework_id查询到的指定id记录信息:" + homeworkList.toString());
                //2, 有这条记录, 就去对比last_modified_date, 如果服务器时间更新, 就update表数据
                if (last_modified_date > wlx_homeworks.get(0).getLast_modified_date()) {
                    WLXGreenDaoUtil.getHomeWorkDao().update(wlxHomeWork);
                }
            } else {
                //无数据,就直接插入数据
                WLXGreenDaoUtil.getHomeWorkDao().insert(wlxHomeWork);
            }
        }

    }

    private void initDataFromDataBase() {
        //已点评
        List<wlx_homework> historyList = WLXGreenDaoUtil.getHomeWorkDao().queryBuilder().where
                (wlx_homeworkDao
                        .Properties.Grade_id.eq(WLXConstant.GRADE_ID), wlx_homeworkDao.Properties
                        .Is_teacher_comment
                        .eq(1)).orderDesc(wlx_homeworkDao.Properties.Homework_id).offset(
                (paging_index - 1) * paging_size).limit(paging_size)
                .list();

        //是否有更多数据,历史或者未点评
        mHasMoreData = historyList.size() != 0;
        if (paging_index == 1) {//下拉刷新,直接加载所有的未点评数据
            mRefreshLayout.endRefreshing();
            //未点评
            List<wlx_homework> homeworkList = WLXGreenDaoUtil.getHomeWorkDao().queryBuilder()
                    .where
                            (wlx_homeworkDao
                                    .Properties.Grade_id.eq(WLXConstant.GRADE_ID), wlx_homeworkDao
                                    .Properties
                                    .Is_teacher_comment
                                    .eq(0)).orderDesc(wlx_homeworkDao.Properties.Homework_id)
                    .list();
            //回复
            List<wlx_homework> homeworkRecallCommentList = WLXGreenDaoUtil.getHomeWorkDao()
                    .queryBuilder().where
                            (wlx_homeworkDao.Properties.Grade_id.eq(WLXConstant.GRADE_ID),
                                    wlx_homeworkDao

                                            .Properties.Is_teacher_comment.eq(1),
                                    wlx_homeworkDao.Properties.Is_family_reply.eq(1)
                                    , wlx_homeworkDao.Properties.Is_replied.eq(0)).orderDesc
                            (wlx_homeworkDao
                                    .Properties.Homework_id)
                    .list();

            if (homeworkList.size() == 0 && historyList.size() == 0) {
                mRefreshLayout.setVisibility(View.GONE);
                mRlContainerEmpty.setVisibility(View.VISIBLE);
                mTvMsg.setText("没有作业点评数据");
                return;
            }


            //未点评数量
            int nocommentsize = homeworkList.size();
            Log.d("未点评--------", nocommentsize + "");
            Log.d("历史----------", historyList.size() + "");
            int mRecallnum = homeworkRecallCommentList.size();
            mNoCommentNum.setText(nocommentsize + "未点评");
            mReplyNum.setText(mRecallnum == 0 ? "暂无回复" : mRecallnum + "回复");
            mHeadView.setVisibility(View.VISIBLE);

            mAdapter.setNoCommitData(homeworkList);
            mAdapter.setHistoryData(historyList);
            mAdapter.notifyDataSetChanged();
        } else {//上拉刷新,只需要刷新历史数据
            mRefreshLayout.endLoadingMore();
            if (mHasMoreData) {
                int count = mAdapter.getCount();
                mAdapter.addHistoryData(historyList);
                mAdapter.notifyDataSetChanged();
                mListView.setSelection(count);
            } else {
                WLXCustomToast.show("没有更多数据");
            }
        }
    }
}
